<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Lookbook extends CI_Controller {

	function __construct()
	{
		parent::__construct();
		$this->load->helper('file');
		$this->load->library('image_lib');
		if(!$this->session->userdata('user_id') && !$this->session->userdata('user_display_name') ):
		redirect('backend');
		endif;
	}

	function index()
	{
		if(!$this->session->userdata('filter_lookbook')):
			$this->session->set_userdata('filter_lookbook','all');
		endif;
		$this->load->library('pagination');
		$offset = $this->uri->segment(4);
		$config['base_url'] = site_url().'/backend/lookbook/index';
		$config['total_rows'] = count($this->get_data($this->session->userdata('filter_lookbook')));
		$config['per_page'] = $this->config->item('per_page');
		$config['uri_segment'] = '4';
		
		$data['urut'] = $this->uri->segment(4);
		$data['title'] = 'Lookbook';
		$data['template'] = 'lookbook/index';
		$data['res'] = $this->get_data($this->session->userdata('filter_lookbook'),$config['per_page'],$offset);
		$this->pagination->initialize($config);
		$this->load->view('backend/index',$data);
	}
	
	function add()
	{
		$this->form_validation->set_rules('judul', 'Judul','required');
		$this->form_validation->set_rules('deskripsi', 'Deskripsi','required');
		$this->form_validation->set_rules('status', 'Status Publikasi','required');
		if ($this->form_validation->run() == FALSE):
			$data['title'] = 'Tambah Lookbook';
			$data['template'] = 'lookbook/add';
			$this->load->view('backend/index',$data);
		else:
			if((!empty($_FILES['image_file']['tmp_name'])) && ($_FILES['image_file']['tmp_name']!="")):
				$data = array(
					'judul' => $this->input->post('judul'),
					'deskripsi' => $this->input->post('deskripsi'),
					'status' => $this->input->post('status'),
					'date_added' => date("Y-m-d")
				);
				$this->uploadImage($data,'add');
				// redirect
				$this->session->set_flashdata('message_type','success');
				$this->session->set_flashdata('message', 'Success');
				redirect('backend/lookbook');
			else:
				$this->session->set_flashdata('message_type','error');
				$this->session->set_flashdata('message', 'Please choose picture file');
				redirect('backend/lookbook/add');
			endif;
		endif;
	}
	
	function edit()
	{
		$lookbook_id = $this->uri->segment(4);
		if($lookbook_id!=''):
			$this->form_validation->set_rules('judul', 'Judul','required');
			$this->form_validation->set_rules('deskripsi', 'Deskripsi','required');
			$this->form_validation->set_rules('status', 'Status Publikasi','required');
			if ($this->form_validation->run() == FALSE):
				$data['lookbook'] = $this->db->where('lookbook_id',$lookbook_id)->get('tb_lookbook')->row();
				$data['title'] = 'Edit Lookbook';
				$data['template'] = 'lookbook/edit';
				$this->load->view('backend/index',$data);
			else:
				$data = array(
					'judul' => $this->input->post('judul'),
					'deskripsi' => $this->input->post('deskripsi'),
					'status' => $this->input->post('status')
				);
				if((!empty($_FILES['image_file']['tmp_name'])) && ($_FILES['image_file']['tmp_name']!="")):
					$this->uploadImage($data,'edit',$this->input->post('lookbook_id'));
					// redirect
					$this->session->set_flashdata('message_type','success');
					$this->session->set_flashdata('message', 'Success');
					redirect('backend/lookbook');
				else:
					$this->db->where('lookbook_id',$lookbook_id)->update('tb_lookbook',$data);
					$this->session->set_flashdata('message_type','success');
					$this->session->set_flashdata('message', 'Success');
					redirect('backend/lookbook');
				endif;
			endif;
		else:
			redirect('backend/lookbook');
		endif;
	}
	
	function uploadImage($data,$param=FALSE,$lookbook_id=FALSE)
	{
		$this->load->helper('file');

		$absolutePath = $this->config->item("absolutePathFile").'look_book/';
		// config untuk upload
		$config['upload_path'] = $this->config->item("upload_path_temp");
		$config['allowed_types'] = 'jpg|jpeg';
		$config['max_size'] = $this->config->item("max_size");
		$config['max_width'] = $this->config->item("max_width");
		$config['max_height'] = $this->config->item("max_height");
		$config['remove_spaces'] = $this->config->item("remove_spaces");

		// inisialisasi library upload
		$this->load->library('upload', $config);
		$large_resize_width = getOption('media_large_width');
		$large_resize_height = getOption('media_large_height');
		$medium_resize_width = getOption('media_medium_width');
		$medium_resize_height = getOption('media_medium_height');
		$thumbnail_size = getOption('media_thumbnail_size');

		// uploading
		if (!$this->upload->do_upload('image_file')):
			print_r($this->upload->display_errors());
		else:
			$uploaded_photo = array('upload_photo' => $this->upload->data());
			$file_uploaded = $uploaded_photo['upload_photo']['file_name'];
			$file_ext = $uploaded_photo['upload_photo']['file_ext'];
			$randName = 'look_'.mt_rand(100000,999999);
			$newName = $randName;
			while(file_exists($config['upload_path'].$newName)):
				$randName = 'look_'.mt_rand(100000,999999);
				$newName = $randName;
			endwhile;
			$fileDate = date("YmdHis");
			$newFileName = $newName.'_'.$fileDate.$file_ext;
			if(!file_exists($config['upload_path'].$newFileName)):
				rename($config['upload_path'].$file_uploaded, $config['upload_path'].$newFileName);
			endif;

			// config untuk resize
			$config['media_path'] = $this->config->item("upload_path").'look_book/';
			$config['image_library'] = $this->config->item("image_library");
			$config['maintain_ratio'] =$this->config->item("maintain_ratio");
			$config['width'] = getOption('media_large_width');
			$config['height'] = getOption('media_large_height');
			$config['source_image'] = $config['upload_path'].$newFileName;

			require_once FCPATH . APPPATH . 'libraries/phpthumb/ThumbLib.inc.php';
			
			$filename_noext = $newName.'_'.$fileDate;
			$thumb = PhpThumbFactory::create($config['upload_path'].$newFileName);
			$thumb->adaptiveResize($large_resize_width, $large_resize_height);
			$thumb->save($absolutePath . $filename_noext . '_'.$large_resize_width.'x'.$large_resize_height.'.jpg', 'jpg');
			$large_image = $filename_noext . '_'.$large_resize_width.'x'.$large_resize_height.'.jpg';
			
			$thumb = PhpThumbFactory::create($config['upload_path'].$newFileName);
			$thumb->adaptiveResize($medium_resize_width, $medium_resize_height);
			$thumb->save($absolutePath . $filename_noext . '_'.$medium_resize_width.'x'.$medium_resize_height.'.jpg', 'jpg');
			$medium_image = $filename_noext . '_'.$medium_resize_width.'x'.$medium_resize_height.'.jpg';
			
			$thumb = PhpThumbFactory::create($config['upload_path'].$newFileName);
			$thumb->adaptiveResize($thumbnail_size, $thumbnail_size);
			$thumb->save($absolutePath . $filename_noext . '_'.$thumbnail_size.'x'.$thumbnail_size.'.jpg', 'jpg');
			$thumb_image = $filename_noext . '_'.$thumbnail_size.'x'.$thumbnail_size.'.jpg';
			unlink($config['upload_path'].$newFileName);
			if($param=='add'):
				$this->db->insert('tb_lookbook',$data);
				$id = $this->db->insert_id();
				$data_image = array(
					'look_img_url' => $large_image,
					'look_img_url_small' => $medium_image,
					'look_img_url_thumb' => $thumb_image
				);
				$this->db->where('lookbook_id',$id)->update('tb_lookbook',$data_image);
			elseif($param=='edit'):
				$cekData = $this->db->where('lookbook_id',$lookbook_id)
						->get('tb_lookbook')
						->row();
				if(count($cekData)>0):
					if(!empty($cekData->look_img_url) && file_exists($absolutePath.$cekData->look_img_url)):
						unlink($absolutePath.$cekData->look_img_url);
					endif;
					if(!empty($cekData->look_img_url_thumb) && file_exists($absolutePath.$cekData->look_img_url_thumb)):
						unlink($absolutePath.$cekData->look_img_url_thumb);
					endif;
					if(!empty($cekData->look_img_url_small) && file_exists($absolutePath.$cekData->look_img_url_small)):
						unlink($absolutePath.$cekData->look_img_url_small);
					endif;
					$data_image = array(
						'look_img_url' => $large_image,
						'look_img_url_small' => $medium_image,
						'look_img_url_thumb' => $thumb_image
					);
					$this->db->where('lookbook_id',$lookbook_id)->update('tb_lookbook',$data_image);
				endif;
			endif;
		endif;
	}
	
	private function get_data($param=FALSE,$limit=FALSE,$offset=FALSE)
	{
		if($limit):
			$this->db->limit($limit,$offset);
		endif;
		if($param=='published'):
			$this->db->where('status','y');
		elseif($param=='unpublished'):
			$this->db->where('status','n');
		endif;
		return $this->db->order_by('lookbook_id','desc')
				->get('tb_lookbook')
				->result();
	}
	
	function ajax_bulk_action($param)
	{
		foreach($_POST["lookbook_id"] as $lookbook_id):
			if($param=='publish'):
				$data = array('status'=>'y');
				$this->db->where('lookbook_id',$lookbook_id)->update('tb_lookbook',$data);
			elseif($param=='unpublish'):
				$data = array('status'=>'n');
				$this->db->where('lookbook_id',$lookbook_id)->update('tb_lookbook',$data);
			elseif($param=='delete'):
				$cekData = $this->db->where('lookbook_id',$lookbook_id)
					->get('tb_lookbook')
					->row();
				if(count($cekData)>0):
					if(!empty($cekData->look_img_url) && file_exists($absolutePath.$cekData->look_img_url)):
						unlink($absolutePath.$cekData->look_img_url);
					endif;
					if(!empty($cekData->look_img_url_thumb) && file_exists($absolutePath.$cekData->look_img_url_thumb)):
						unlink($absolutePath.$cekData->look_img_url_thumb);
					endif;
					if(!empty($cekData->look_img_url_small) && file_exists($absolutePath.$cekData->look_img_url_small)):
						unlink($absolutePath.$cekData->look_img_url_small);
					endif;
					$this->db->where('lookbook_id', $lookbook_id)->delete('tb_lookbook');
				endif;
			endif;
		endforeach;
	}
	
	function filter_lookbook($param)
	{
		if($param):
			$this->session->set_userdata('filter_lookbook',$param);
		endif;
		redirect('backend/lookbook');
	}
}